import logging
import os
import subprocess

from ocup.database import db

logger = logging.getLogger("ocup")


class SystemInfo:
    def __init__(self):
        self.name = None
        self.version = None
        self.firewalld_enabled = None
        self.openssh_permit_root = None
        self.release_config = "/etc/os-release"
        self.openssh_config = "/etc/ssh/sshd_config"

    def resolve_system_info(self):
        self.resolve_release()
        self.resolve_firewalld()
        self.resolve_openssh()

    def disable_selinux(self):
        # logger.debug("")
        subprocess.run(["/usr/sbin/setenforce", "0"])

    def resolve_release(self):
        try:
            with open(self.release_config) as f:
                release_content = f.readlines()
        except IOError as e:
            logger.error(e)
            raise e
        for l in release_content:
            if l.startswith("NAME="):
                self.name = l.split("=")[1].strip().strip('"').strip()
            if l.startswith("VERSION="):
                self.version = l.split("=")[1].strip().strip('"').strip()
        db.set("os_name", self.name)
        db.set("os_version", self.version)

    def resolve_firewalld(self):
        result = subprocess.run(['/usr/bin/systemctl', 'is-enabled', 'firewalld'], stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE)
        if result.returncode == 0:
            self.firewalld_enabled = True
        else:
            self.firewalld_enabled = False
        db.set("firewalld_enabled", self.firewalld_enabled)

    def resolve_openssh(self):
        try:
            with open(self.openssh_config) as f:
                openssh_content = f.readlines()
        except IOError as e:
            logger.error(e)
            raise e
        for line in openssh_content:
            if line.startswith("PermitRootLogin "):
                # 以最后一个配置为主
                self.openssh_permit_root = line.split()[1].strip()
        db.set("openssh_permit_root", self.openssh_permit_root)

    def restore_system_config(self):
        self.restore_firewalld()
        self.restore_openssh()
        self.restore_dbus()

    @staticmethod
    def restore_firewalld():
        if db.get("firewalld_enabled"):
            result = subprocess.run(['/usr/bin/systemctl', 'enable', 'firewalld'], stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE)
            if result.returncode != 0:
                logger.error(result.stderr)

    def restore_openssh(self):
        self.openssh_permit_root = db.get("openssh_permit_root")
        if db.get("openssh_permit_root") is not None:
            try:
                with open("/etc/ssh/sshd_config.d/01-ocup.conf", "w") as f:
                    config = """# generated by ocup.\nPermitRootLogin {}\n""".format(self.openssh_permit_root)
                    f.write(config)
            except IOError as e:
                logger.error(e)

    @staticmethod
    def restore_dbus():
        dbus_service = "/etc/systemd/system/dbus.service"
        dbus_broker_service = "/usr/lib/systemd/system/dbus-broker.service"
        if not os.path.exists(dbus_service):
            if os.path.exists(dbus_broker_service):
                logger.info("link dbus service")
                os.symlink(dbus_broker_service, dbus_service)
            else:
                logger.error("{} don\'t exist".format(dbus_broker_service))
                logger.error("failed to do dbus link")
